package com.xls.minio.service.impl;

import com.xls.base.exception.BusinessException;
import com.xls.minio.feign.RoomImageService;
import com.xls.minio.service.MinioService;
import io.minio.*;
import io.minio.messages.Item;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;


@RefreshScope
@Service
public class MinioServiceImpl implements MinioService {

    @Autowired
    private RoomImageService roomImageService;

    @Value("${minio.endpoint}")
    private String endpoint;
    @Value("${minio.accessKey}")
    private String accessKey;
    @Value("${minio.secretKey}")
    private String secretKey;
    @Value("${minio.bucketName}")
    private String bucketName;

    @Override
    public String uploadAvatar(MultipartFile file) {
        try {
            MinioClient minioClient = MinioClient.builder()
                    .endpoint(endpoint)
                    .credentials(accessKey, secretKey)
                    .build();
            InputStream inputStream = file.getInputStream();
            String uuid = UUID.randomUUID().toString().replace("-", "");
            //String filename = "avatar/" + uuid + file.getOriginalFilename();
            String filename = "avatar/" + uuid + "file.png";
            PutObjectArgs putObjectArgs = PutObjectArgs.builder()
                    .bucket(bucketName)
                    .object(filename)
                    .contentType(file.getContentType())
                    .stream(inputStream, inputStream.available(), -1)
                    .build();
            minioClient.putObject(putObjectArgs);
            inputStream.close();
            return endpoint + "/" + bucketName + "/" + filename;
        } catch (Exception e) {
            throw new BusinessException(999, "上传文件失败");
        }
    }

    @Override
    public void removeAvatar(String filename) {
        try {
            MinioClient minioClient = MinioClient.builder()
                    .endpoint(endpoint)
                    .credentials(accessKey, secretKey)
                    .build();
            minioClient.removeObject(RemoveObjectArgs.builder().bucket(bucketName).object(filename).build());
        } catch (Exception e) {
            throw new BusinessException(999, "删除文件失败");
        }
    }

    @Override
    @Transactional
    public String uploadRoomImage(MultipartFile file, String id) {
        try {
            MinioClient minioClient = MinioClient.builder()
                    .endpoint(endpoint)
                    .credentials(accessKey, secretKey)
                    .build();
            InputStream inputStream = file.getInputStream();
            //String uuid = UUID.randomUUID().toString().replace("-", "");
            String filename = "room/" + id + "/" + file.getOriginalFilename();
            PutObjectArgs putObjectArgs = PutObjectArgs.builder()
                    .bucket(bucketName)
                    .object(filename)
                    .contentType(file.getContentType())
                    .stream(inputStream, inputStream.available(), -1)
                    .build();
            minioClient.putObject(putObjectArgs);
            inputStream.close();
            String url = endpoint + "/" + bucketName + "/" + filename;
            //openfeign
            roomImageService.uploadRoomImage(id, url);
            return url;
        } catch (Exception e) {
            throw new BusinessException(999, "上传文件失败");
        }
    }

    @Override
    @Transactional
    public void removeRoomImage(String filename, String id) {
        try {
            MinioClient minioClient = MinioClient.builder()
                    .endpoint(endpoint)
                    .credentials(accessKey, secretKey)
                    .build();
            RemoveObjectArgs build = RemoveObjectArgs
                    .builder()
                    .bucket(bucketName)
                    .object("room/" + id + "/" + filename)
                    .build();
            //openfeign
            String url = endpoint + "/" + bucketName + "/" + "room/" + id + "/" + filename;
            roomImageService.removeRoomImage(id, url);

            minioClient.removeObject(build);
        } catch (Exception e) {
            throw new BusinessException(999, "删除文件失败");
        }

    }

    @Override
    public List<String> getRoomImage(String id) {
        List<String> urls = new ArrayList<>();
        try {
            MinioClient minioClient = MinioClient.builder()
                    .endpoint(endpoint)
                    .credentials(accessKey, secretKey)
                    .build();
            ListObjectsArgs build = ListObjectsArgs.builder().bucket(bucketName).prefix("/room/" + id + "/").build();
            Iterable<Result<Item>> results = minioClient.listObjects(build);
            for (Result<Item> next : results) {
                urls.add("http://192.168.121.128:9000/" + bucketName + next.get().objectName());
            }
        } catch (Exception e) {
            throw new BusinessException(999, "获取文件失败");
        }
        return urls;
    }
}
